//
//  Entity.m
//  objectiverecord
//
//  Created by Gang.Wang on 12-5-18.
//  Copyright (c) 2012年 yuike. All rights reserved.
//

#import "Entity.h"
#import "Entity+Local.h"
#import "header.h"
#import "ObjectiveRecordDef.h"
#import "EntityManager.h"

@implementation Entity

@synthesize rowId;
@synthesize dbProvider;
@synthesize table_name;
@synthesize column_name_array;
@synthesize column_type_array;


- (void)finalize 
{
  YRelease(dbProvider)
  [super finalize];
}

- (void)dealloc
{
    YRelease(dbProvider)
    
    YRelease( table_name)
    YRelease(column_name_array)
    YRelease(column_type_array)
    YRelease(rowId)
    [super dealloc];
}

- (void) save {
  //if rowId is 0, insert, otherwise update
  NSString * tableName = [EntityManager getTableNameWithClassName:table_name];
    
  NSString *sql = nil;
  if(rowId == 0) {
    sql = [NSString stringWithFormat:@"INSERT INTO %@ (",tableName];
    for (int i = 0; i < [column_name_array count]; i++) {
      sql = [NSString stringWithFormat:@"%@ %@", sql, [column_name_array objectAtIndex:i]];
      if (i < [column_name_array count]-1) {
        sql = [NSString stringWithFormat:@"%@, ", sql];
      }
    }
    sql = [NSString stringWithFormat:@"%@ ) VALUES (", sql];
    for (int i = 0; i < [column_name_array count]; i++) {
      if ([[column_type_array objectAtIndex:i] isEqualToString:@"TEXT"] || 
          [[column_type_array objectAtIndex:i] isEqualToString:@"DATETIME"] || 
          [[column_type_array objectAtIndex:i] isEqualToString:@"BLOB"]) {
        sql = [NSString stringWithFormat:@"%@ '%@'", sql, [self valueForKey:[column_name_array objectAtIndex:i]]];
      } else {
        sql = [NSString stringWithFormat:@"%@ %@", sql, [self valueForKey:[column_name_array objectAtIndex:i]]];
      }
      if (i < [column_name_array count]-1) {
        sql = [NSString stringWithFormat:@"%@, ", sql];
      }
    }
    sql = [NSString stringWithFormat:@"%@ );", sql];
    [self setRowId:[dbProvider executeQuery:sql withArgument:nil]];
  } else {
    sql = [NSString stringWithFormat:@"UPDATE %@ SET ",tableName];
    for (int i = 0; i < [column_name_array count]; i++) {
      if ([[column_name_array objectAtIndex:i] isEqualToString:@"rowid"]) {
        // nothing to do 
      } else if ([[column_type_array objectAtIndex:i] isEqualToString:@"TEXT"] || 
          [[column_type_array objectAtIndex:i] isEqualToString:@"DATETIME"] || 
          [[column_type_array objectAtIndex:i] isEqualToString:@"BLOB"]) {
        sql = [NSString stringWithFormat:@"%@ %@ = '%@'", sql, [column_name_array objectAtIndex:i], [self valueForKey:[column_name_array objectAtIndex:i]]];
      } else {
        sql = [NSString stringWithFormat:@"%@ %@ = %@", sql, [column_name_array objectAtIndex:i], [self valueForKey:[column_name_array objectAtIndex:i]]];
      }
      if (i < [column_name_array count]-1 && ![[column_name_array objectAtIndex:i] isEqualToString:@"rowid"]) {
        sql = [NSString stringWithFormat:@"%@, ", sql];
      }
    }
    sql = [NSString stringWithFormat:@"%@ WHERE rowid = %@;", sql, rowId];
    [dbProvider executeQuery:sql withArgument:nil];
  }
}


-(id) init
{
    self = [super init];
    if (self) 
    {
        NSString * className = [self className];
        if (![className endswith:_OBJECTIVEREVORD_TABLE_]) {
            
            NSString * exceptionMessage = [NSString stringWithFormat:@"You must named \"%@\" endWith \"%@\", eg: rename \"%@\" to \"%@\"", 
                                           className,
                                           _OBJECTIVEREVORD_TABLE_,
                                           className,
                                           [NSString stringWithFormat:@"%@%@", className, _OBJECTIVEREVORD_TABLE_]];
            
            [NSException raise:NSInternalInconsistencyException format:@"Exception:%@", exceptionMessage];
        }
    }
    return self;
}
@end

